﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
using System.Collections;

namespace DevPhone.Controls
{
    public class SelectedItemsTypeConverter : TypeConverter
    {
        public override object ConvertFrom(
            ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            string list = value as string;
            if (list != null)
                return list.Split(';');

            return base.ConvertFrom(context, culture, value);
        }

        public override bool CanConvertFrom(
            ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string))
                return true;

            return base.CanConvertFrom(context, sourceType);
        }

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(string))
            {
                if (value == null)
                {
                    return String.Empty;
                }
                var result = string.Empty;
                foreach (var item in (IList)value)
                {
                    var it = item as ListPickerItem;
                    if (it != null)
                    {
                        result += it.Content + ";";
                    }
                    if (result.EndsWith(";", StringComparison.Ordinal))
                    {
                        result = result.Substring(0, result.Length - 1);
                    }
                }
                return result;
            }
            return TypeConverters.ConvertTo(this, value, destinationType);
        }

    }
}
